﻿using System;
using RedBit.UserVoice.OAuth;
using Hammock;
using Newtonsoft.Json.Linq;

namespace RedBit.UserVoice.Services
{
    public class UVOAuthService : BaseUVApi
    {
        public static void GetRequestToken(Action<RequestToken> handler)
        {
            var credentials = BuildCredentials();

            var client = new RestClient
            {
                Authority = string.Format(UserVoiceConstants.URL_TEMPLATE, UserVoiceAPI.AppName),

                Credentials = credentials
            };

            var request = new RestRequest
            {
                Path = UserVoiceConstants.REQUEST_TOKEN_SUFFIX,
            };
            client.BeginRequest(request, HandleOAuthRequestToken, handler);
        }

        private static void HandleOAuthRequestToken(RestRequest rq, RestResponse rs, object token)
        {
            JObject obj = JObject.Parse(rs.Content);
            var requestToken = new RequestToken()
            {
                Key = obj["token"]["oauth_token"].Value<string>(),
                Secret = obj["token"]["oauth_token_secret"].Value<string>()
            };

            var handler = token as Action<RequestToken>;
            handler(requestToken);

        }
    }
}
